import axios from 'axios';

import store from './store';
import router from './router';
import * as types from './store/types';

axios.defaults.timeout = 5000;
axios.defaults.baseURL = "/api/v1";

axios.interceptors.request.use(
  config => {
    if (store.getters.isLogin) {
      config.headers.Authorization = `USER ${store.getters.email} ${store.getters.access_token}`;
    }
    return config;
  },
  err => {
    console.error('axios interceptors request error', err);
    return Promise.reject(err);
  }
);

axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        store.commit(types.LOGOUT);
        router.replace({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath,
          }
        });
      }
    }
    //TODO: 此处返回 error , error.response, error.response.data 区别较大，需校验
    return Promise.reject(error);
  }
);

export default axios;